import { createRouter, createWebHashHistory } from "vue-router";
import usage from "@/utils/usage";

const routes = [
  {
    path: "/",
    redirect: "/loginView",
  },
  {
    path: "/loginView",
    name: "loginView",
    component: () => import("../views/LoginView.vue"),
  },
  {
    path: "/homeView",
    name: "homeView",
    component: () => import("../views/HomeView.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 设置路由守卫 to前往路由信息，from要离开的路由
// next参数是一个方法 有三种next()继续执行跳转，next('/login')跳转指定路由，next(false)停止跳转
router.beforeEach((to, from, next) => {
  let toName = to.name;
  // 校验白名单 可以把白名单的name放这里进行判断
  let notPermission = ["loginView"];
  // 判断白名单中是否有这个name有的话就直接跳
  if (notPermission.includes(toName)) {
    if (toName === "loginView") {
      usage.removeToken();
    }
    next();
  } else {
    // 判断路由中token是否存在，存在就继续，不存在跳转到登录页。
    //一定要判断要跳转的页面不能是next跳的页面 会造成死循环的
    if (usage.getToken() || toName === "loginView") {
      next();
    } else {
      next("/");
    }
  }
});

export default router;
